import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import {
  queryOrderList,
  addOrder,
  editOrder,
  delOrder,
} from './service';

import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    add: Effect;
    edit: Effect;
    del: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'logisCenterDeliveryRecoverList',

  state: {
    data: {
      list: [],
      count: 0,
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryOrderList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: data.body,
      });
    },
    * add({ payload }, { call, put }) {
      const response = yield call(addOrder, payload.params);
      const data = fetchValidation(response);
      if (data) {
        message.success('添加成功');
        yield put({
          type: 'fetch',
          payload: {},
        });
      }
    },
    * edit({ payload }, { call, put }) {
      const response = yield call(editOrder, payload.params);
      const data = fetchValidation(response);
      if (data) {
        message.success('修改成功');
        yield put({
          type: 'fetch',
          payload: payload.query,
        });
      }
    },
    * del({ payload }, { call, put }) {
      const response = yield call(delOrder, payload.params);
      const data = fetchValidation(response);
      if (data) {
        message.success('删除成功');
        yield put({
          type: 'fetch',
          payload: payload.query,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
  },
};

export default Model;
